import React, {useState} from 'react';
import {UserCreateParam} from "../data.d";
import {Form, Button, Modal, Input} from 'antd';

export interface CreateFormProps {
  onCancel: (flag?: boolean, formVals?: UserCreateParam) => void;
  onSubmit: (value: UserCreateParam) => void;
  createUserModalVisible: boolean;
}

const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 7},
  wrapperCol: { span: 13},
}

const CreateForm: React.FC<CreateFormProps> = (props) => {
   const [formValues, setFormValues] = useState<UserCreateParam>({
     loginName: '', name: '', password: '', role: 'admin|user'
   });
   const [form] = Form.useForm();
   const {
     onSubmit: handleCreate,
     onCancel: handleCreateModalVisible,
     createUserModalVisible,
   } = props;

   const handleRealCreate = async () => {
     const fieldValue = await form.validateFields();
     setFormValues({...formValues, ...fieldValue});
     handleCreate({...formValues, ...fieldValue})
   };

   const renderFooter = () => {
     return (
       <>
         <Button onClick={() => handleCreateModalVisible(false)}>取消</Button>
         <Button type="primary" onClick={() => handleRealCreate()}>创建</Button>
         </>
     );
   };

   return (
     <Modal
       width={640}
       bodyStyle={{padding: '32px 40px 48px'}}
       destroyOnClose
       title="创建新用户"
       visible={createUserModalVisible}
       footer={renderFooter()}
       onCancel={() => handleCreateModalVisible(false)}
       >
       <Form
         {...formLayout}
         form={form}
         initialValues={{
           loginName: formValues.loginName,
           name: formValues.name,
           password: formValues.password,
           role: formValues.role,
         }}
       >
         <FormItem
          name="loginName"
          label="登陆名"
         >
           <Input />
         </FormItem>
         <FormItem
           name="password"
           label="密码"
         >
           <Input />
         </FormItem>
         <FormItem
           name="name"
           label="姓名"
         >
           <Input />
         </FormItem>
         <FormItem
           name="role"
           label="角色"
         >
           <Input />
         </FormItem>
       </Form>
     </Modal>
   );
};

export default CreateForm
